define([
	"UtilDir/util",
	"UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
	"UtilDir/loading",
	"http://api.tianditu.gov.cn/api?v=4.0&tk=aeb17a8215786a5dd17f5f9c92bebc0c",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang"
    ],function(Util, Tool, SelectOrg, SearchBlock, Loading){

	var getQhSiteClassResultController = function(){
		return getServer() + "/qh/qhSiteClassResults";
	};
	/**
	 * 页面初始化
	 */
	var tdMap, rectTool;
	var init = function(qhDrillDataQuerySupport){
		initcreateProvince();
		initcreateProvince2();
		initcreateProvince3();
		downloadFile();
		uploadFile();
		queryBtnBind();
		initMap();
		qhDrillDataQuerySupport.init(tdMap, rectTool);
	};
	var initcreateProvince = function () {
		var html = '<option value="" selected>请选择</option>';
		$("#citySelect").append(html);
		$("#areaSelect").append(html);
		$.ajax({
			url: getServer() + "/divisions/root/subdivisions",
			contentType: "application/json",
			type: "get",
			success: function (data) {
				$.each(data, function (idx, item) {
					html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
				});
				$("#provinceSelect").append(html);
			}
		});
		$("#provinceSelect").change(function () {
			var html = '<option value="" selected>请选择</option>';
			$("#citySelect option").remove();
			//$("#citySelect").append(html);
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
				$("#citySelect").append(html);
				$("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
				return;
			}
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#citySelect").append(html);
				}
			});
		});
		$("#citySelect").change(function () {
			//if ($(this).val() == "") return;
			var html = '<option value="" selected>请选择</option>';
			$("#areaSelect option").remove();
			//$("#areaSelect").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#areaSelect").append(html);
				}
			});
		});
	}
	var initcreateProvince2 = function () {
		var html = '<option value="" selected>请选择</option>';
		$("#citySelect2").append(html);
		$("#areaSelect2").append(html);
		$.ajax({
			url: getServer() + "/divisions/root/subdivisions",
			contentType: "application/json",
			type: "get",
			success: function (data) {
				$.each(data, function (idx, item) {
					html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
				});
				$("#provinceSelect2").append(html);
			}
		});
		$("#provinceSelect2").change(function () {
			var html = '<option value="" selected>请选择</option>';
			$("#citySelect2 option").remove();
			//$("#citySelect2").append(html);
			$("#areaSelect2 option").remove();
			$("#areaSelect2").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
				$("#citySelect2").append(html);
				$("#citySelect2").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
				return;
			}
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#citySelect2").append(html);
				}
			});
		});
		$("#citySelect2").change(function () {
			//if ($(this).val() == "") return;
			var html = '<option value="" selected>请选择</option>';
			$("#areaSelect2 option").remove();
			//$("#areaSelect2").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#areaSelect2").append(html);
				}
			});
		});
	}
	var initcreateProvince3 = function () {
		var html = '<option value="" selected>请选择</option>';
		$("#citySelect3").append(html);
		$("#areaSelect3").append(html);
		$.ajax({
			url: getServer() + "/divisions/root/subdivisions",
			contentType: "application/json",
			type: "get",
			success: function (data) {
				$.each(data, function (idx, item) {
					html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
				});
				$("#provinceSelect3").append(html);
			}
		});
		$("#provinceSelect3").change(function () {
			var html = '<option value="" selected>请选择</option>';
			$("#citySelect3 option").remove();
			//$("#citySelect3").append(html);
			$("#areaSelect3 option").remove();
			$("#areaSelect3").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
				$("#citySelect3").append(html);
				$("#citySelect3").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
				return;
			}
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#citySelect3").append(html);
				}
			});
		});
		$("#citySelect3").change(function () {
			//if ($(this).val() == "") return;
			var html = '<option value="" selected>请选择</option>';
			$("#areaSelect3 option").remove();
			//$("#areaSelect3").append(html);
			var divisionId = $(this).find("option:selected").attr("exid");
			$.ajax({
				url: getServer() + "/divisions/" + divisionId + "/subdivisions",
				contentType: "application/json",
				type: "get",
				success: function (data) {
					$.each(data, function (idx, item) {
						html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
					});
					$("#areaSelect3").append(html);
				}
			});
		});
	}

	var downloadFile = function () {
		$("#button-export").on("click", function () {
			var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "", area = $("#areaSelect").val() || "";
			window.location.href = getQhSiteClassResultController() + "/download0?province=" + province + "&city=" + city + "&area=" + area;;
		});
	}
	var uploadFile = function(){
		// 要上传的文件的后缀名数组
		var minList = [];
		// 要上传的文件的文件名数组
		var nameList = [];
		// var maxList = ["dbf","prj","shp","shx"];
		// 获取文件名
		$("#button-selectfile").on("change", function () {
			var uploadinputFiles = document.getElementById("button-selectfile").files;
			minList = [];nameList = [];
			var text = "";
			for (var i = 0; i < uploadinputFiles.length; i++){
				console.log("uploading: " + uploadinputFiles[i].name);
				text += uploadinputFiles[i].name+"\n";
				// 获取这个文件的后缀名
				minList.push(uploadinputFiles[i].name.slice(uploadinputFiles[i].name.length-3,uploadinputFiles[i].name.length));
				nameList.push(uploadinputFiles[i].name.split(".")[0]);
			}
			$("#commentInfo").val(text);
		});

		$("#button-import").on("click", function () {
			var uploadinput = document.getElementById("button-selectfile");
			if (uploadinput.value == "") {
				Util.alert("上传前请先选择文件!");
				return;
			}else if(!judgeIsOnce(minList)){
				Util.alert('上传数量限制:.dbf、.prj、.shp、.shx文件各1个;.sbn、.sbx、.shp.xml文件至多一个。');
				return;
			}else if(!judgeName(nameList)){
				Util.alert("文件名请保持一致！");
				return;
			}
			var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "", area = $("#areaSelect").val() || "";
			if(province == "" && city == "" && area == ""){//zyt
				province = "全国";
				city = "全国";
				area = "全国";
			}
			/*if(province == ""){
				Util.alert("请选择场地所在省份!");
				return;
			}
			if(city == ""){
				Util.alert("请选择场地所在市!");
				return;
			}
			if(area == ""){
				Util.alert("请选择场地所在区县!");
				return;
			}*/
			var formData = new FormData();
			for(var i = 0; i < uploadinput.files.length; i++){
				formData.append('files', uploadinput.files[i]);
			}
			formData.append("province", province);
			formData.append("city", city);
			formData.append("area", area);
			loading.show();
			$.ajax({
				url: getQhSiteClassResultController() + "/upload",
				data: formData,
				processData: false, //因为data值是FormData对象，不需要对数据做处理。
				contentType: false,
				type: "POST",
				success: function (data) {
					loading.close();
					uploadinput.value = null;
					$("#provinceSelect").val(""),
					$("#citySelect").val(""),
					$("#areaSelect").val(""),
					$("#commentInfo").val(""),
					Util.alert(data);
				},
				error: function(xhr, state, errorThrown){
					loading.close();
					Util.alert("上传数据出现异常!");
				}
			});
		});
	}

	var queryBtnBind = function(){
		$("#operatePanelButton").click(function () {
			var operatePanel = $("#operatePanel");
			if (operatePanel.is(":visible")) {
				operatePanel.css("display", "none");
			} else {
				operatePanel.css("display", "block");
				$("#operatePanel2").css("display", "none");
				$("#operatePanel3").css("display", "none");
				$("#siteClassLayersImg").attr("src", "/qhwx/static/app/images/tucengoff.png");
				clearPolygons();
			}
		});

		$("#siteClassLayers2").click(function () {
			var sclImg = $("#siteClassLayersImg"), operatePanel2 = $("#operatePanel2");
			if (operatePanel2.is(":visible")) {
				sclImg.attr("src", "/qhwx/static/app/images/tucengoff.png");
				//clearPolygons();
				operatePanel2.css("display", "none");
			} else {
				sclImg.attr("src", "/qhwx/static/app/images/tucengon.png");
				operatePanel2.css("display", "block");
				//getSiteClassResultData();
				//createAffiliatedFileNameGridGrid();
				global_flag = "2";
			}
			$("#operatePanel").css("display", "none");
			$("#operatePanel3").css("display", "none");
		});

		$("#siteClassLayers3").click(function () {
			var operatePanel3 = $("#operatePanel3");
			if (operatePanel3.is(":visible")) {
				//clearPolygons();
				operatePanel3.css("display", "none");
			} else {
				operatePanel3.css("display", "block");
				//getSiteClassResultData();
				//createAffiliatedFileNameGridGrid();
				global_flag = "3";
			}
			$("#operatePanel").css("display", "none");
			$("#operatePanel2").css("display", "none");
			$("#siteClassLayersImg").attr("src", "/qhwx/static/app/images/tucengoff.png");
		});

		$("#operatePanel2CloseBtn").click(function () {
			$("#siteClassLayersImg").attr("src", "/qhwx/static/app/images/tucengoff.png");
			$("#operatePanel2").css("display", "none");
		});

		$("#operatePanel3CloseBtn").click(function () {
			$("#siteClassLayersImg").attr("src", "/qhwx/static/app/images/tucengoff.png");
			$("#operatePanel3").css("display", "none");
		});

		$("#closePanelBtn").click(function () {
			$("#operatePanel").css("display", "none");
		});

		$("#button-closeForm").click(function () {
			$("#operatePanel").css("display", "none");
		});

		$("#btnSearch").click(function () {
			//createAffiliatedFileNameGridGrid("2");
			getSiteClassResultData("2");
			isSearchData = true;
		});
		$("#btnSearch3").click(function () {
			//createAffiliatedFileNameGridGrid("3");
			getSiteClassResultData("3");
			isSearchData = true;
		});

		$("#qhFieldInfoBtn").click(function () {
			showFieldInfo();
		});
		$("#qhFieldInfoClose").click(function () {
			$('#qhFieldInfo').hide(200);
		});
	};
	var judgeIsOnce = function (list) {
		// ["dbf","prj","shp","shx"];
		var dbf = 0;var prj = 0;var shp = 0;var shx = 0;var sbn = 0;var sbx = 0;var xml = 0;
		$.each(list,function (idx,item) {
			if(item == 'dbf') dbf++;
			if(item == 'prj') prj++;
			if(item == 'shp') shp++;
			if(item == 'shx') shx++;
			if(item == 'sbn') sbn++;
			if(item == 'sbx') sbx++;
			if(item == 'xml') xml++;
		})
		//if(dbf == 1 && prj == 1 && shp == 1 && shx == 1 && sbn < 2 && sbx < 2 && xml < 2) return true;
		if(dbf == 1 && prj < 2 && shp == 1 && shx == 1) return true;
		else return false;
	};
	var judgeName = function (list) {
		var name = list[0];
		var result = list.filter(function (item) {
			return item == name;
		})
		if(result.length == list.length) return true;
		else return false;
	}

	/*var getSiteClassResultData = function (flag) {
		clearPolygons();
		loading2.show();
		var bounds = tdMap.getBounds(), sw = bounds.getSouthWest(), ne = bounds.getNorthEast(), zoom = tdMap.getZoom();
		var province = $("#provinceSelect2").val(), city = $("#citySelect2").val(), area = $("#areaSelect2").val();
		flag == "3" && (province = $("#provinceSelect3").val(), city = $("#citySelect3").val(), area = $("#areaSelect3").val());
		var formData = {province: province, city: city, area: area, zoom: zoom, isHaveAuthorityControl: flag == "3" ? "0" : "1",
			bounds: sw.lng + " " + sw.lat + "," + ne.lng + " " + ne.lat, zoom: zoom};
		$.ajax({
			url: getQhSiteClassResultController() + "/searchQhSiteClassResults",
			data: formData,
			//contentType: "application/json",
			type: "POST",
			success: function (result) {
				loading2.close();
				if (typeof(result) == 'string') {
					Util.alert(result);
					return;
				}
				var data = result.data;
				console.log(data);
				if (data && data.length) {
					affiliatedFileNames = []; fileName2feature = {};
					var affiliatedFileName, local_points = [];
					for (var idx = 0;idx < data.length;idx++) {
						affiliatedFileName = data[idx].affiliatedFileName;
						!isFileNameInObj(affiliatedFileName) && (affiliatedFileNames.push({affiliatedFileName: affiliatedFileName}));
						!fileName2feature[affiliatedFileName] && (fileName2feature[affiliatedFileName] = []);
						var coords_str = data[idx].coordinates;
						var geometries = coords_str.split("|"), geo_points = [];
						for (var k = 0;k < geometries.length;k++) {
							var __coords = geometries[k].split("#"), _geo_points = [];
							for (var m = 0;m < __coords.length;m++) {
								var _coords = __coords[m].split(", "), points = [];
								for (var n = 0;n < _coords.length;n++) {
									var coord = _coords[n].split(" ");
									var lon = parseFloat(coord[0]), lat = parseFloat(coord[1]), lonlat = new T.LngLat(lon, lat);
									points.push(lonlat);
									//if (!lon || !lat) console.log(idx, k, lon, lat, coord);
									local_points.push(lonlat);
								}
								_geo_points.push(points);
							}
							geo_points.push(_geo_points);
						}
						var polygon = new T.Polygon(geo_points, {
							color: "#860404",
							weight: 1,
							opacity: 0.5,
							fillColor: rank_color[data[idx].usaClassi],
							fillOpacity: 0.7,
							affiliatedFileName: affiliatedFileName,
							usaClassi: data[idx].usaClassi,
							district: data[idx].province + data[idx].city + data[idx].area
						});
						tdMap.addOverLay(polygon);
						polygon.addEventListener("click", function (obj) {
							console.log(obj);
							var target = obj.target, bounds = target.getBounds(), center = obj.lnglat/!*bounds.getCenter()*!/, district = target.options.district;
							global_infoWin.setContent(/!*district + ": " + *!/rank_name[target.options.usaClassi]);
							tdMap.openInfoWindow(global_infoWin, center);
						});
						global_polygons.push(polygon);
						fileName2feature[affiliatedFileName].push(polygon);
						//break;
					}
					//global_polygons = global_polygons.sort(compare("usaClassi"));
					//console.log(global_polygons);
					//filterLargeNumberPolygons();
					//tdMap.setViewport(local_points);
				}
			},
			error: function(xhr, state, errorThrown){
				loading2.close();
				Util.alert("查询数据出现异常!");
			}
		});
	};*/
	var getSiteClassResultData = function (flag) {
		var bounds = tdMap.getBounds(), sw = bounds.getSouthWest(), ne = bounds.getNorthEast(), zoom = tdMap.getZoom();
		var province = $("#provinceSelect2").val(), city = $("#citySelect2").val(), area = $("#areaSelect2").val();
		if (!(province == "" && city == "" && area == "")) {
			Util.alert("系统暂时仅支持全国数据查询!");
			return;
		}
		//clearPolygons();
		loading2.show();
		flag == "3" && (province = $("#provinceSelect3").val(), city = $("#citySelect3").val(), area = $("#areaSelect3").val());
		var formData = {province: province, city: city, area: area, zoom: zoom, isHaveAuthorityControl: flag == "3" ? "0" : "1",
			bounds: sw.lng + " " + sw.lat + "," + ne.lng + " " + ne.lat, zoom: zoom};
		$.ajax({
			url: getQhSiteClassResultController() + "/searchQhSiteClassResults",
			data: formData,
			type: "POST",
			success: function (result) {
				loading2.close();
				if (typeof(result) == 'string') {
					Util.alert(result);
					return;
				}
				var data = result.data;
				console.log(data);
				clearPolygons();
				if (data && data.length) {
					var local_points = [];
					for (var idx = 0;idx < data.length;idx++) {
						var coords_str = data[idx].coordinates;
						var geometries = coords_str.split("|"), geo_points = [];
						for (var k = 0;k < geometries.length;k++) {
							var __coords = geometries[k].split("#"), _geo_points = [];
							for (var m = 0;m < __coords.length;m++) {
								var _coords = __coords[m].split(", "), points = [];
								for (var n = 0;n < _coords.length;n++) {
									var coord = _coords[n].split(" ");
									var lon = parseFloat(coord[0]), lat = parseFloat(coord[1]), lonlat = new T.LngLat(lon, lat);
									points.push(lonlat);
									local_points.push(lonlat);
								}
								_geo_points.push(points);
							}
							geo_points.push(_geo_points);
						}
						var polygon = new T.Polygon(geo_points, {
							color: "#860404",
							weight: 1,
							opacity: 0.5,
							fillColor: rank_color[data[idx].usaClassi],
							fillOpacity: 0.7,
							usaClassi: data[idx].usaClassi,
							district: data[idx].province + data[idx].city + data[idx].area
						});
						tdMap.addOverLay(polygon);
						polygon.addEventListener("click", function (obj) {
							console.log(obj);
							var target = obj.target, bounds = target.getBounds(), center = obj.lnglat/*bounds.getCenter()*/, district = target.options.district;
							global_infoWin.setContent(/*district + ": " + */rank_name[target.options.usaClassi]);
							tdMap.openInfoWindow(global_infoWin, center);
						});
						global_polygons.push(polygon);
					}
				}
			},
			error: function(xhr, state, errorThrown){
				loading2.close();
				Util.alert("查询数据出现异常!");
			}
		});
	};
	var createAffiliatedFileNameGridGrid = function(flag) {
		var affiliatedFileNameGrid = "affiliatedFileNameGrid" + flag;
		$("#" + affiliatedFileNameGrid).datagrid({
			url: getQhSiteClassResultController() + "/queryQhSiteClassResultsByFileName",
			method: "GET",
			fitColumns: true,
			autoRowHeight: false,
			nowrap: false,
			idField: 'id',
			columns:[[
				{field:"ck", checkbox: true},
				{
					field:'affiliatedFileName',
					title:'文件名称',
					width:'60%',
					align:'center',
					formatter: function (value, rowData, rowIndex) {
						var fileName = rowData.affiliatedFileName, idx = fileName.lastIndexOf("--");
						//(idx != -1) ? (idx = idx + 2) : (idx = 4);
						//(idx != -1) ? (idx = 5) : (idx = 4);
						if (idx != -1) {

						} else {
							var _c = fileName.substring(4, 5);
							if (_c == "_") idx = 5;
							else idx = 4;
							fileName = (fileName ? (fileName.substring(idx)) : "");
						}
						if (flag == "2") {
							return '<a href="#" onclick="_downloadSilteClassResultFile(\'' + rowData.affiliatedFileName + '\');if(window.event&&window.event.stopPropagation)window.event.stopPropagation();else window.event.cancelBubble=true;"> ' + fileName + ' </a> '
						} else if (flag == "3") {
							return fileName;
						}
					}
				},
				{
					field:'createTime',
					title:'上传日期',
					width:'40%',
					align:'center',
					sortable: true
				},
			]],
			toolbar: flag == "3" ? [] : (flag == "2" ? [{
				iconCls: 'fa fa-trash-o',
				text:"删除",
				handler: function(){
					deleteFileData();
				}
			}] : []),
			onBeforeLoad: function () {
				$(".datagrid-pager.pagination").hide();
			},
			onLoadSuccess: function () {
				$("#" + affiliatedFileNameGrid).datagrid('selectAll');
				var operatePanel_checkbox = 'operatePanel' + flag + ' input[type=checkbox]';
				$('#' + operatePanel_checkbox).click(function () {
					var rowIndex = $(this).parent().parent().parent().attr("datagrid-row-index");
					var rows = $('#' + affiliatedFileNameGrid).datagrid('getRows'), row = rows[rowIndex];
					if ($(this).is(":checked")) {
						console.log("addOverLay");
						for (let i = 0; i < global_polygons.length; i++) {
							if (global_polygons[i].options.affiliatedFileName == row.affiliatedFileName) {
								tdMap.addOverLay(global_polygons[i]);
								fileName2feature[row.affiliatedFileName].push(global_polygons[i]);
							}
						}
					} else {
						console.log("removeOverLay");
						for (let i = 0; i < global_polygons.length; i++) {
							if (global_polygons[i].options.affiliatedFileName == row.affiliatedFileName) tdMap.removeOverLay(global_polygons[i]);
						}
						fileName2feature[row.affiliatedFileName] = [];
					}
				});
			},
			queryParams: {
				province: flag == "2" ? $("#provinceSelect2").val() : (flag == "3" ? $("#provinceSelect3").val() : ""),
				city: flag == "2" ? $("#citySelect2").val() : (flag == "3" ? $("#citySelect3").val() : ""),
				area: flag == "2" ? $("#areaSelect2").val() : (flag == "3" ? $("#areaSelect3").val() : ""),
				isHaveAuthorityControl: flag == "3" ? "0" : "1",
			},
			pagination: true,
			pageSize: 1000,
			pageList: [ 1000],
		});
	};
	window._downloadSilteClassResultFile = function (affiliatedFileName) {
		var pca = affiliatedFileName.split("_");
		console.log(affiliatedFileName, pca);
		var province = pca[0], city = pca[1], area = pca[2];
		window.location.href = getQhSiteClassResultController() + "/download?province=" + province + "&city=" + city + "&area=" + area + "&affiliatedFileName=" + encodeURIComponent(affiliatedFileName);
		/*
		$.ajax({
			url: getQhSiteClassResultController() + "/download?province=" + province + "&city=" + city + "&area=" + area,
			contentType: false,
			type: "GET",
			success: function (data) {
				Util.alert(data);
			}
		});*/

	};
	var deleteFileData = function () {
		var affiliatedFileNameGrid = "affiliatedFileNameGrid" + global_flag;
		var rows = $("#" + affiliatedFileNameGrid).datagrid("getSelections"), _rows = $('#' + affiliatedFileNameGrid).datagrid('getRows');
		if (rows.length == _rows.length) {
		} else {
			rows = [];
			var operatePanel_checkbox = 'operatePanel' + global_flag + ' input[type=checkbox]';
			$('#' + operatePanel_checkbox).each(function () {
				if ($(this).is(":checked")) {
					var rowIndex = $(this).parent().parent().parent().attr("datagrid-row-index");
					var row = _rows[rowIndex];
					row && rows.push(row);
				}
			});
		}
		console.log(rows)

		if (rows == null || rows.length == 0) {
			Util.alert("请选择一行数据!");
			return;
		}
		Util.confirm("是否要删除选中的数据?", function () {
			var fileNames = "";
			$.each(rows, function (i, row) {
				fileNames += row.affiliatedFileName + ",";
			});
			fileNames = fileNames.substr(0, fileNames.length - 1);
			console.log("fileNames: ", fileNames);
			loading3.show();
			$.ajax({
				url: getQhSiteClassResultController() + "/deleteQhSiteClassResultsByFileNames?fileNames=" + fileNames,
				type: "get",
				success: function (data) {
					loading3.close();
					Util.confirm("删除成功!", function () {
						createAffiliatedFileNameGridGrid(global_flag);
						getSiteClassResultData(global_flag);
					}, function () {
						return;
					});
					var buttons = $(".modal-dialog.modal-sm").find(".modal-footer").children("button");
					if (buttons) {
						if (buttons.length == 2) {
							buttons.eq(0).html("确定");
							buttons.eq(1).hide();
						} else if (buttons.length == 4) {
							buttons.eq(2).html("确定");
							buttons.eq(3).hide();
						}
					}
				},
				error: function(xhr, state, errorThrown){
					loading3.close();
					Util.alert("删除数据出现异常!");
				}
			});
		}, function () {
			return;
		});
	};
	var isFileNameInObj = function (fileName) {
		for (let i = 0; i < affiliatedFileNames.length; i++) {
			if (affiliatedFileNames[i].affiliatedFileName == fileName) return true;
		}
		return false;
	};
	var compare = function (property) {
		return function (a, b) {
			var value1 = transUsaClassi(a.options[property]);
			var value2 = transUsaClassi(b.options[property]);
			return value2 - value1;
		}
	};
	var transUsaClassi = function (usaClassi) {
		if(usaClassi == "Ⅰ"){
			return 1;
		} else if (usaClassi == "Ⅱ") {
			return 2;
		} else if (usaClassi == "Ⅲ") {
			return 3;
		} else if (usaClassi == "Ⅳ") {
			return 4;
		} else if (usaClassi == "Ⅴ") {
			return 5;
		}
		return -1;
	};

	var showFieldInfo = function () {
		$("#qhFieldInfo").show();
		var data = [
			/*{"字段名": "province", "数据类型": "varchar(255)", "是否必填": "是", "注释": "省级行政区", "示例": "北京市"},
			{"字段名": "city", "数据类型": "varchar(255)", "是否必填": "是", "注释": "市级行政区", "示例": "北京市"},
			{"字段名": "area", "数据类型": "varchar(255)", "是否必填": "是", "注释": "县级行政区", "示例": "东城区"},
			{"字段名": "object_id_1", "数据类型": "varchar(32)", "是否必填": "否", "注释": "object_id_1", "示例": "1"},
			{"字段名": "object_id", "数据类型": "varchar(32)", "是否必填": "否", "注释": "object_id", "示例": "1"},
			{"字段名": "usa_classi", "数据类型": "varchar(10)", "是否必填": "否", "注释": "场地类型", "示例": "I0"},
			{"字段名": "shape_leng", "数据类型": "double(20,7)", "是否必填": "否", "注释": "shape_leng", "示例": "291023.548983"},
			{"字段名": "shape_le_1", "数据类型": "double(20,7)", "是否必填": "否", "注释": "shape_le_1", "示例": "291018.566898"},
			{"字段名": "shape_area", "数据类型": "varchar(100)", "是否必填": "否", "注释": "shape_area", "示例": "855870522.174"},
			{"字段名": "coordinates", "数据类型": "varchar(100)", "是否必填": "是", "注释": "经纬度坐标", "示例": "MULTIPOLYGON (((89118.76289999858 3831353.6537999995, 166906.41840000078 3728748.0319999997, 175426.0188000016 3720493.0154999997)))"},*/
			//{"序号": "1", "数据类型": "longtext", "是否必填": "是", "注释": "经纬度坐标", "示例": "MULTIPOLYGON (((115.89890347669503 39.56583970735696, 115.9013738940018 39.56561527405075, 115.90137098205221 39.56560217890379)))"},
			{"序号": "1", "字段描述": "场地类型", "是否必填": "是", "注释": "综合考虑断层、软土等地震地质破坏不利因素，将工程场地划分为Ⅰ、Ⅱ、Ⅲ、Ⅳ、Ⅴ五类，其中Ⅰ、Ⅱ、Ⅲ、Ⅳ分别对应《建筑抗震设计规范》中4.1.6条中根据土层等效剪切波速和场地覆盖层厚度确定的Ⅰ、Ⅱ、Ⅲ、Ⅳ类场地，与已探明的活断层距离小于等于10公里的场地定义为第Ⅴ类。", "示例": "Ⅱ"},
			//{"序号": "2", "数据类型": "double(20,7)", "是否必填": "否", "注释": "shape_leng", "示例": "291023.548983"},
			//{"序号": "3", "数据类型": "double(20,7)", "是否必填": "否", "注释": "shape_le_1", "示例": "291018.566898"},
			//{"序号": "4", "数据类型": "double(20,7)", "是否必填": "否", "注释": "shape_area", "示例": "855870522.174"},
		];
		$("#qhFieldInfoGrid").datagrid({
			data: data,
			method: "GET",
			//fitColumns: true,
			autoRowHeight: false,
			nowrap: false,
			idField: 'id',
			columns:[[
				//{field:"ck",checkbox:true},
				{
					field:'序号',
					title:'序号',
					width:'10%',
					align:'center',
				},
				{
					field:'字段描述',
					title:'字段描述',
					width:'14%',
					align:'center',

				},
				{
					field:'是否必填',
					title:'是否必填',
					width:'14%',
					align:'center',
				},
				{
					field:'注释',
					title:'注释',
					width:'50%',
					align:'center',
				},
				{
					field:'示例',
					title:'示例',
					width:'15%',
					align:'center',
				},
			]],
			pagination: false,
			pageSize: 10
		});
	};

	var fileName2feature = {}, affiliatedFileNames = [];
	var global_polygons = [];
	//var rank_color = {"Ⅰ": "#A87001", "Ⅱ": "#DF9E66", "Ⅲ": "#F6C568", "Ⅳ": "#FFEABD", "Ⅴ": "#FFFFBF"};
	//var rank_color = {"Ⅰ": "#B2001F", "Ⅱ": "#DF0029", "Ⅲ": "#EE7C6B", "Ⅳ": "#F5A89A", "Ⅴ": "#FCDAD5"};
	var rank_color = {"1": "#B2001F", "2": "#DF0029", "3": "#EE7C6B", "4": "#f5a89a", "9": "#FCDAD5", "10": "#4B85ED"};
	var rank_name = {"1": "I0类场地", "2": "I类场地", "3": "II类场地", "4": "III类场地", "9": "IV类场地", "10": "水体"};
	var loading = Loading({text : "正在上传数据..."}), loading2 = Loading({text : "正在查询数据..."}), loading3 = Loading({text : "正在删除数据..."});
	var global_infoWin = new T.InfoWindow(""), global_flag, isSearchData = false, isFromZoomend = false;
	var initMap = function() {
        var mapH = document.body.clientHeight - $(".pd-search-container").height() - 10;
        $("#qhSiteClassMap").height(mapH);

		var vec_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/d9ffc071-50dd-4780-a617-673d17921e22/wmts?service=wmts&request=gettile&version=1.0.0&layer=vec&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var cva_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/13f8b69d-98dc-4276-bbf0-9c4c372acabc/wmts?service=wmts&request=gettile&version=1.0.0&layer=cva&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var config = {
            projection: 'EPSG:4326',
            minZoom: 4,
            layers: [vec_layer, cva_layer]
        };
        tdMap = new T.Map('qhSiteClassMap', config), zoom = 4;
        tdMap.centerAndZoom(new T.LngLat(106.34766, 34.37971), zoom);

        var control=new T.Control.Zoom();
        tdMap.addControl(control);

        //创建比例尺控件对象
        var scale = new T.Control.Scale();
        tdMap.addControl(scale);

		//rectTool = new T.RectangleTool(tdMap);

		/*tdMap.addEventListener("zoomend", filterLargeNumberPolygons);
		tdMap.addEventListener("moveend", filterLargeNumberPolygons);*/

		tdMap.addEventListener("moveend", moveEndLoadLevelSiteData);
		tdMap.addEventListener("zoomend", zoomEndLoadLevelSiteData);
	};
	var clearPolygons = function () {
		_clearPolygons();
		global_polygons = [];
	};
	var _clearPolygons = function () {
		for (let i = 0; i < global_polygons.length; i++) {
			tdMap.removeOverLay(global_polygons[i]);
		}
	};

	var levels = ["1-3", "4-6", "7-9", "10-13", "14-16", "17-18"], global_level = "4-6";
	var zoomEndLoadLevelSiteData = function (e) {
		isFromZoomend = true;
		if (!isSearchData) return ;
		if (e.type == "zoomend") getSiteClassResultData(global_flag);
		console.log("zoomEndLoadLevelSiteData");
	};
	var moveEndLoadLevelSiteData = function (e) {
		if (!isSearchData || isFromZoomend) {
			isFromZoomend = false;
			return ;
		}
		console.log("moveEndLoadLevelSiteData");
		getSiteClassResultData(global_flag);
	};
	
	var filterLargeNumberPolygons = function (e) {
		if (!e) return;
		if (e.type == "zoomend") return;
		var suit_num = 1000, suit_zoom = 10, zoom = tdMap.getZoom();
		_clearPolygons();
		var bounds = tdMap.getBounds(), sw = bounds.getSouthWest(), ne = bounds.getNorthEast();
		var cPoints = [{x: sw.lat, y: sw.lng}, {x: ne.lat, y: sw.lng}, {x: ne.lat, y: ne.lng}, {x: sw.lat, y: ne.lng}];
		var lng_lats, _lng_lats, _global_polygons = [];
		for (const eKey in fileName2feature) _global_polygons = _global_polygons.concat(fileName2feature[eKey]);
		_global_polygons = _global_polygons.sort(compare("usaClassi"));
		//console.log(_global_polygons);
		for (let i = 0; i < _global_polygons.length; i++) {
			lng_lats = _global_polygons[i].getLngLats();
			var points = [];
			for (let j = 0; j < lng_lats.length; j++) {
				_lng_lats = lng_lats[j];
				var _points = [];
				for (let k = 0; k < _lng_lats.length; k++) {
					_points.push({x: _lng_lats[k].lat, y: _lng_lats[k].lng});
				}
				points.push(_points);
			}
			for (let l = 0; l < points.length; l++) {
				var _points = points[l];
				if (zoom >= suit_zoom) {
					if (isPolygonsOverlap(cPoints, _points)) {
						console.log(_global_polygons[i].options.usaClassi);
						tdMap.addOverLay(_global_polygons[i]);
						suit_num--;
					} else {
						tdMap.removeOverLay(_global_polygons[i]);
					}
				} else {
					if (suit_num > 0) {
						if (isPolygonsOverlap(cPoints, _points)) {
							tdMap.addOverLay(_global_polygons[i]);
							suit_num--;
						} else {
							tdMap.removeOverLay(_global_polygons[i]);
						}
					} else {
						return;
					}
				}
			}
		}
		console.log("size:", (1000 - suit_num), "zoom: ", zoom);
	};
	var isPolygonsOverlap = function (plyA, plyB) {
		return isPolygonsIntersectant(plyA, plyB) || isPointInPolygonBidirectional(plyA, plyB);
	}
	//判断两多边形线段是否相交
	var isSegmentsIntersectant = function (segA, segB) {//线线
		const abc = (segA[0].x - segB[0].x) * (segA[1].y - segB[0].y) - (segA[0].y - segB[0].y) * (segA[1].x - segB[0].x);
		const abd = (segA[0].x - segB[1].x) * (segA[1].y - segB[1].y) - (segA[0].y - segB[1].y) * (segA[1].x - segB[1].x);
		if (abc * abd >= 0) {
			return false;
		}
		const cda = (segB[0].x - segA[0].x) * (segB[1].y - segA[0].y) - (segB[0].y - segA[0].y) * (segB[1].x - segA[0].x);
		const cdb = cda + abc - abd;
		return !(cda * cdb >= 0);
	}
	//判断两多边形边界是否相交
	var isPolygonsIntersectant = function (plyA, plyB) {//面面
		for (let i = 0, il = plyA.length; i < il; i++) {
			for (let j = 0, jl = plyB.length; j < jl; j++) {
				const segA = [plyA[i], plyA[i === il - 1 ? 0 : i + 1]];
				const segB = [plyB[j], plyB[j === jl - 1 ? 0 : j + 1]];
				if (isSegmentsIntersectant(segA, segB)) {
					return true;
				}
			}
		}
		return false;
	}
	//判断点是否在另一平面图中
	var isPointInPolygon = function (point, polygon) {

		//下述代码来源：http://paulbourke.net/geometry/insidepoly/，进行了部分修改
		//基本思想是利用射线法，计算射线与多边形各边的交点，如果是偶数，则点在多边形外，否则
		//在多边形内。还会考虑一些特殊情况，如点在多边形顶点上，点在多边形边上等特殊情况。

		var N = polygon.length;
		var boundOrVertex = true; //如果点位于多边形的顶点或边上，也算做点在多边形内，直接返回true
		var intersectCount = 0; //cross points count of x
		var precision = 2e-10; //浮点类型计算时候与0比较时候的容差
		var p1, p2; //neighbour bound vertices
		var p = point; //测试点

		p1 = polygon[0]; //left vertex
		for (var i = 1; i <= N; ++i) { //check all rays
			if (p.x == p1.x && p.y == p1.y) {
				return boundOrVertex; //p is an vertex
			}

			p2 = polygon[i % N]; //right vertex
			if (p.y < Math.min(p1.y, p2.y) || p.y > Math.max(p1.y, p2.y)) { //ray is outside of our interests
				p1 = p2;
				continue; //next ray left point
			}

			if (p.y > Math.min(p1.y, p2.y) && p.y < Math.max(p1.y, p2.y)) { //ray is crossing over by the algorithm (common part of)
				if (p.x <= Math.max(p1.x, p2.x)) { //x is before of ray
					if (p1.y == p2.y && p.x >= Math.min(p1.x, p2.x)) { //overlies on a horizontal ray
						return boundOrVertex;
					}

					if (p1.x == p2.x) { //ray is vertical
						if (p1.x == p.x) { //overlies on a vertical ray
							return boundOrVertex;
						} else { //before ray
							++intersectCount;
						}
					} else { //cross point on the left side
						var xinters = (p.y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y) + p1.x; //cross point of x
						if (Math.abs(p.x - xinters) < precision) { //overlies on a ray
							return boundOrVertex;
						}

						if (p.x < xinters) { //before ray
							++intersectCount;
						}
					}
				}
			} else { //special case when ray is crossing through the vertex
				if (p.y == p2.y && p.x <= p2.x) { //p crossing over p2
					var p3 = polygon[(i + 1) % N]; //next vertex
					if (p.y >= Math.min(p1.y, p3.y) && p.y <= Math.max(p1.y, p3.y)) { //p.y lies between p1.y & p3.y
						++intersectCount;
					} else {
						intersectCount += 2;
					}
				}
			}
			p1 = p2; //next ray left point
		}

		if (intersectCount % 2 == 0) { //偶数在多边形外
			return false;
		} else { //奇数在多边形内
			return true;
		}
	}
	//判断两多变形是否存在点与区域的包含关系(A的点在B的区域内或B的点在A的区域内)
	var isPointInPolygonBidirectional = function (plyA, plyB) {//面面
		let [a, b] = [false, false];
		a = plyA.some(item => isPointInPolygon(item, plyB));
		if (!a) {
			b = plyB.some(item => isPointInPolygon(item, plyA));
		}
		return a || b;
	}

	return {
		init:init
	};
});
